import { defineStore } from 'pinia'
import { anyGet } from '@/network'

interface UserInfo {
  id: string
  username: string
  realName?: string
  email?: string
  phone?: string
  avatar?: string
}

interface UserState {
  token: string
  userInfo: UserInfo | null
  permissions: string[]
}

export const useUserStore = defineStore('user', {
  state: (): UserState => ({
    token: '',
    userInfo: null,
    permissions: [],
  }),
  getters: {
    isLoggedIn: (state) => !!state.token,
    hasPermission: (state) => (permission: string) => {
      // 如果没有权限数据，在开发环境下提供默认权限
      if (state.permissions.length === 0) {
        // 提供默认的活码管理权限
        const defaultPermissions = [
          'qrcode:create',
          'qrcode:update',
          'qrcode:delete',
          'qrcode:view',
          'system:user:list',
          'system:user:create',
          'system:user:update',
          'system:user:delete',
          'system:user:view',
          'system:user:assign',
          'system:user:reset',
          'system:user:auth:view',
          'system:user:auth:create',
          'system:user:auth:update',
          'system:user:auth:delete'
        ];
        return defaultPermissions.includes(permission);
      }
      return state.permissions.includes(permission)
    },
  },
  actions: {
    setToken(token: string) {
      this.token = token
    },
    setUserInfo(userInfo: UserInfo) {
      this.userInfo = userInfo
    },
    setPermissions(permissions: string[]) {
      this.permissions = permissions
    },
    async fetchUserInfo() {
      try {
        const response = await anyGet('/api/auth/userinfo')
        if (response.code === 200 || response.success) {
          this.setUserInfo(response.data.userInfo)
          this.setPermissions(response.data.permissions || [])
        }
      } catch (error) {
        console.error('获取用户信息失败:', error)
      }
    },
    logout() {
      this.token = ''
      this.userInfo = null
      this.permissions = []
      localStorage.removeItem('permissions')
    },
  },
  persist: {
    key: 'user',
    paths: ['token', 'userInfo', 'permissions'],
  },
})